<template>
  <div :id="containerId" :style="styleObj"></div>
</template>
<script>
export default {
  name: "UEditor",
  props: {
    // 编辑器容器id
    containerId: {
      default: "hz-UEcontainer",
      type: String,
    },
    // 输入的最大字数限制
    maximumWords: {
      default: 10000,
      type: Number,
    },
    // 初始化数据值
    initContent: {
      default: "",
      type: String,
    },
    // 输入事件
    onChange: {
      default: () => {},
      type: Function,
    },
    readonly: {
      default: false,
      type: Boolean,
    },
    editorHeight: {
      default: "500px",
      type: String,
    },
    editorWidth: {
      default: "800px",
      type: String,
    },
  },
  data() {
    return {
      styleObj: {
        height: this.editorHeight,
        width: this.editorWidth,
      },
      ueInstance: null,
    };
  },
  methods: {
    getBody(ue, time = 10) {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (ue.body) {
            resolve(ue.body);
          } else {
            if (time > 0) {
              time--;
              this.getBody(ue);
            } else {
              console.log("初始化失败");
            }
          }
        }, 500);
      });
    },
    setContents(ue) {
      const html = ue.getContent();
      ue.focus();
      this.onChange(html);
    },
    // 初始化编辑器
    async initEditor() {
      const { UE } = window;
      try {
        /* 加载之前先执行删除操作，否则如果存在页面切换，
        再切回带编辑器页面重新加载时不刷新无法渲染出编辑器 */
        UE.delEditor(this.containerId);
      } catch (e) {
        console.warn("UE.delEditor error: ", e);
      }
      const ue = UE.getEditor(this.containerId, {
        readonly: this.readonly,
        autoHeightEnabled: false,
        initialContent: this.initContent,
        wordCount: true,
        maximumWords: this.maximumWords,
      });
      this.ueInstance = ue;
      ue.addListener("contentChange", () => {
        if (ue) {
          setTimeout(() => {
            this.setContents(ue);
          }, 0);
        }
      });
      try {
        let body = await this.getBody(ue);
        body.addEventListener("paste", () => {
          setTimeout(() => {
            this.setContents(ue);
          }, 0);
        });
      } catch (error) {
        console.log(error);
      }
      // this.$nextTick(() => {
      //   console.log(ue.body);
      //   ue.body.addEventListener("paste", function(event) {
      //     console.log("粘贴", event.clipboardData.getData("html"));
      //   });
      // });
    },
  },

  mounted() {
    this.initEditor();
  },
};
</script>
<style scoped lang="scss"></style>
